﻿//Url Ping Tool
//By Alon Havivi(havivi@gmail.com, http://havivi.blogspot.com/) 
//For full source code and Terms Of Use,
//visit http://www.codeplex.com/upt

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Net;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Navigation;

namespace SNSREAAL.iD.SharePoint.Features.UrlPingTool.WebControls
{
    public class UrlPingToolControl : System.Web.UI.WebControls.WebControl
    {
        protected override void OnLoad(EventArgs e)
        {

            SPWeb web = SPContext.Current.Web;

            Table table = new Table();
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            table.CellPadding = 2;
            table.CellSpacing = 0;
            table.Style.Add("FONT-FAMILY", "Arial, Helvetica, Sans Serif");
            table.Style.Add("Width", "100%");
            row = RenderRow("<b>Scope</b>", "<b>Name</b>", "<b>Title</b>", "<b>URL</b>", "<b>Duration</b>", "<b>Size</b>", "<b>Status</b>");
            table.Rows.Add(row);


            string url = web.Url;
            string[] page = url.Split('/');
            string ping = PingUrl(url);
            string[] splitPing = ping.Split('#');
            string size = string.Empty;
            string status = string.Empty;
            string duration = string.Empty;

            duration = splitPing[0];
            size = splitPing[1];
            status = splitPing[2];

            row = RenderRow("Web",
                            web.Title,
                            page[page.Length - 1],
                            "<a href=\"" + url + "\" title=\"" + url + "\">Open URL</a>",
                            duration,
                            size,
                            status);
            table.Rows.Add(row);

            duration = "";
            size = "";
            status = "";
            SPListCollection webLists = web.Lists;
            foreach (SPList list in webLists)
            {
                try
                {
                    SPViewCollection listViews = list.Views;
                    foreach (SPView view in listViews)
                    {
                        if (view.Title != string.Empty)
                        {
                            url = web.Url + "/" + view.Url;
                            ping = PingUrl(url);
                            splitPing = ping.Split('#');
                            duration = splitPing[0];
                            size = splitPing[1];
                            status = splitPing[2];
                            row = RenderRow("List",
                                              list.Title,
                                              view.Title,
                                              "<a href=\"" + url + "\" title=\"" + url + "\">Open URL</a>",
                                              duration,
                                              size,
                                              status);
                            table.Rows.Add(row);
                        }
                    }
                }
                catch (Exception ex)
                {
                    table.Rows.Add(RenderErrorRow(ex.Message));
                }
            }

            if (PublishingWeb.IsPublishingWeb(web))
            {
                Guid pagesListId = PublishingWeb.GetPagesListId(web);
                SPList pagesList = web.Lists[pagesListId];
                SPListItemCollection pagesListItems = pagesList.Items;
                foreach (SPListItem pageItem in pagesListItems)
                {
                    try
                    {
                        if (PublishingPage.IsPublishingPage(pageItem))
                        {
                            PublishingPage publishingPage = PublishingPage.GetPublishingPage(pageItem);

                            page = publishingPage.Url.Split('/');
                            url = web.Url + "/" + publishingPage.Url;
                            ping = PingUrl(url);
                            splitPing = ping.Split('#');
                            duration = splitPing[0];
                            size = splitPing[1];
                            status = splitPing[2];
                            row = RenderRow("Page",
                                              publishingPage.Title,
                                              page[page.Length - 1],
                                              "<a href=\"" + url + "\" title=\"" + url + "\">Open URL</a>",
                                              duration,
                                              size,
                                              status);
                            table.Rows.Add(row);

                        }
                    }
                    catch (Exception ex)
                    {
                        table.Rows.Add(RenderErrorRow(ex.Message));
                    }
                }
            }


            SPNavigationNodeCollection quickLaunchNodes = web.Navigation.QuickLaunch;
            foreach (SPNavigationNode node in quickLaunchNodes)
            {
                try
                {
                    if (web.ServerRelativeUrl == "/")
                    {
                        url = web.Url + node.Url;
                    }
                    else
                    {
                        url = web.Url.Replace(web.ServerRelativeUrl, "") + node.Url;
                    }
                    page = node.Url.Split('/');
                    ping = PingUrl(url);
                    splitPing = ping.Split('#');
                    duration = splitPing[0];
                    size = splitPing[1];
                    status = splitPing[2];
                    row = RenderRow("Quick Launch",
                                      node.Title,
                                      page[page.Length - 1],
                                      "<a href=\"" + url + "\" title=\"" + url + "\">Open URL</a>",
                                      duration,
                                      size,
                                      status);
                    table.Rows.Add(row);
                }
                catch (Exception ex)
                {
                    table.Rows.Add(RenderErrorRow(ex.Message));
                }
            }

            SPNavigationNodeCollection globalNodes = web.Navigation.GlobalNodes;
            foreach (SPNavigationNode node in globalNodes)
            {
                try
                {
                    if (!node.IsExternal)
                    {
                        if (web.ServerRelativeUrl == "/")
                        {
                            url = web.Url + node.Url;
                        }
                        else
                        {
                            url = web.Url.Replace(web.ServerRelativeUrl, "") + node.Url;
                        }
                        page = node.Url.Split('/');
                        ping = PingUrl(url);
                        splitPing = ping.Split('#');
                        duration = splitPing[0];
                        size = splitPing[1];
                        status = splitPing[2];
                        row = RenderRow("Global Nodes",
                                          node.Title,
                                          page[page.Length - 1],
                                          "<a href=\"" + url + "\" title=\"" + url + "\">Open URL</a>",
                                          duration,
                                          size,
                                          status);
                        table.Rows.Add(row);
                    }
                }
                catch (Exception ex)
                {
                    table.Rows.Add(RenderErrorRow(ex.Message));
                }
            }

            this.Controls.Add(table);


        }

        private static TableRow RenderRow(string scope,
                                          string name,
                                          string title,
                                          string url,
                                          string duration,
                                          string size,
                                          string status)
        {
            TableRow row = new TableRow();
            row.Style.Add("Width", "100%");
            row.Cells.Add(RenderCell(scope));
            row.Cells.Add(RenderCell(name));
            row.Cells.Add(RenderCell(title));
            row.Cells.Add(RenderCell(url));
            row.Cells.Add(RenderCell(duration));
            row.Cells.Add(RenderCell(size));
            row.Cells.Add(RenderCell(status));
            return row;
        }


        private static TableRow RenderErrorRow(string err)
        {
            TableRow row = new TableRow();
            row.Style.Add("Width", "100%");
            TableCell cell = new TableCell();
            cell.ColumnSpan = 7;
            cell.CssClass = "ms-vh2";
            cell.Style.Add("Color", "#000000");
            cell.Controls.Add(new LiteralControl(err));
            row.Cells.Add(cell);
            return row;
        }


        private static TableCell RenderCell(string text)
        {
            TableCell cell = new TableCell();
            cell.CssClass = "ms-vh2";
            cell.Style.Add("Color", "#000000");
            cell.Controls.Add(new LiteralControl(text));
            return cell;
        }

        private string PingUrl(string url)
        {
            try
            {
                WebRequest webRequest = WebRequest.Create(url);
                webRequest.UseDefaultCredentials = true;
                webRequest.Timeout = 90000;
                WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
                webHeaderCollection.Add("Trace", "1");
                webRequest.Headers = webHeaderCollection;
                DateTime startTime = DateTime.Now;
                WebResponse webResponse = webRequest.GetResponse();
                string status = (((HttpWebResponse)webResponse).StatusDescription);
                DateTime stopTime = DateTime.Now;
                TimeSpan duration = stopTime - startTime;
                string contentLength = GetResponseContentLength(webResponse.ContentLength);
                webResponse.Close();
                return duration.ToString().Substring(6) + "#" + contentLength + "#" + status;
            }
            catch (Exception ex)
            {
                return "##" + ex.Message;
            }
        }

        public static string GetResponseContentLength(long ContentLength)
        {
            if (ContentLength > 1048575)
            {
                return String.Format("{0:0.00 mb}", (Convert.ToDecimal((Convert.ToDouble(ContentLength) / 1024) / 1024)));
            }
            else
            {
                return String.Format("{0:0.00 kb}", (Convert.ToDecimal(Convert.ToDouble(ContentLength) / 1024)));
            }
        }

    }


}
